﻿<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%@ page import="java.io.*,com.knife.news.model.Constants,com.knife.news.object.User"%>
<%@ page import="java.text.SimpleDateFormat,java.util.Vector,java.net.URLEncoder,java.util.Arrays,com.knife.tools.FileOperation"%>
<%@ page import="com.knife.news.object.Site,com.knife.news.logic.SiteService,com.knife.news.logic.impl.SiteServiceImpl"%>
<%
	int popedom = 0;
	try {
		//User user = (User) ActionContext.getContext().getSession().getAttribute(Constants.SESSION_USER);
		User user = (User) session.getAttribute(Constants.SESSION_USER);
		if (user != null) {
			popedom = user.getPopedom();
		} else {
			response.sendRedirect("/admin.ad");
		}
	} catch (Exception e) {
		response.sendRedirect("/admin.ad");
	}
%>
<%
	request.setCharacterEncoding("UTF-8");
	response.setHeader("Pragma", "No-cache");//HTTP 1.1
	response.setHeader("Cache-Control", "no-cache");//HTTP 1.0
	response.setHeader("Expires", "0");//防止被proxy
%>
<html>
	<head>
		<title>文件管理</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<link type="text/css" rel="StyleSheet" href="face.css" />
	</head>
	<body>
		<%
			String resultInfo = "";
			String URLpath = null;
			String path = request.getParameter("path");
			String sid = request.getParameter("sid");
			Site site=new Site();
			SiteService siteDAO=SiteServiceImpl.getInstance();
			if(sid!=null){
				site=siteDAO.getSiteById(sid);
			}else{
				site=siteDAO.getSite();
			}
			boolean error = false;
			//if path==null
			if (path == null) {
				path = request.getRealPath("/html/"+site.getPub_dir()+"/");
				//path=application.getRealPath("/upload/");
			} else {
				//path=request.getRealPath(path);
				if (path.equals("images") || path.equals("office")
						|| path.equals("others")) {
					path = request.getRealPath("/html/"+site.getPub_dir()+"/" + path);
				}
				if (path.length() < request.getRealPath("/html/"+site.getPub_dir()+"/").length()) {
					path = request.getRealPath("/html/"+site.getPub_dir()+"/");
				}
			}
			//path=URLDecoder.decode();
			path = FileOperation.unicodeToChinese(path);
			if (request.getParameter("errorPath") != null) {
				path = request.getParameter("errorPath");
			}
			//download
			if (request.getParameter("download") != null) {
				String filePath = request.getParameter("download");
				filePath = FileOperation.unicodeToChinese(filePath);
				File file = null;
				FileInputStream fis = null;
				BufferedOutputStream os = null;
				try {
					file = new File(filePath);
					fis = new FileInputStream(file);
					os = new BufferedOutputStream(response.getOutputStream());
					fis = new java.io.FileInputStream(filePath);
					response.setContentType("application/octet-stream");
					response.setContentLength((int) file.length());
					response.setHeader(
							"Content-Disposition",
							"attachment; filename=\""
									+ new String(file.getName().getBytes(
											"UTF-8"), "iso8859-1") + "\"");
					byte[] buff = new byte[1024 * 10];
					int i = 0;
					while ((i = fis.read(buff)) > 0) {
						os.write(buff, 0, i);
					}
					fis.close();
					os.flush();
					os.close();
				} catch (Exception ex) {
					out.print("<div class='error'>"
							+ new String(ex.getMessage()) + "</div>");
					if (fis != null)
						fis.close();
					if (os != null)
						os.close();
				}
			}//end
				//delete files
			else if ((request.getParameter("submit") != null)
					&& ("Delete".equals(request.getParameter("parameter")))) {
				String[] files = request.getParameterValues("selfile");
				path = request.getParameter("path");//如果path以POST发过来就不要过滤了
				if (files == null || files.length < 1) {
					out.print("<div class='error'>没有选择任何文件</div>");
				} else {
					resultInfo = FileOperation.delFile(files);
					out.print(resultInfo);
				}
			}//end
				// Move selected file(s)
			else if ((request.getParameter("submit") != null)
					&& ("MoveFile".equals(request.getParameter("parameter")))) {
				String mvFilePath = request.getParameter("mvFilePath");
				String[] files = request.getParameterValues("selfile");
				if (files == null || files.length < 1) {
					out.print("<div class='error'>没有选择任何文件</div>");
				} else if (mvFilePath == null || mvFilePath.length() < 1) {
					out.print("<div class='error'>没有获得移动的新路径</div>");
				} else {
					resultInfo = FileOperation.mvFile(files, mvFilePath);
					out.print(resultInfo);
				}
			}//end
				//Copy selected file(s)
			else if ((request.getParameter("submit") != null)
					&& ("CopyFile".equals(request.getParameter("parameter")))) {
				String cpFilePath = request.getParameter("cpFilePath");
				String[] files = request.getParameterValues("selfile");
				if (files == null || files.length < 1) {
					out.print("<div class='error'>没有选择任何文件</div>");
				} else if (cpFilePath == null || cpFilePath.length() < 1) {
					out.print("<div class='error'>没有获得复制的新路径</div>");
				} else {
					resultInfo = FileOperation.cpFile(files, cpFilePath, path);
					out.print(resultInfo);
				}
			}//end
				//Create folder
			else if ((request.getParameter("submit") != null)
					&& ("CreateFolder".equals(request.getParameter("parameter")))) {
				String crFolderName = request.getParameter("crFolderName");
				path = request.getParameter("path");//如果path以POST发过来就不要过滤了
				String info = null;
				if (path == null || path.length() < 1) {
					out.print("<div class='error'>没有获得当前路径</div>");
				} else if (crFolderName == null || crFolderName.length() < 1) {
					out.print("<div class='error'>没有获得创建文件夹的名称</div>");
				} else {
					resultInfo = FileOperation.crFolder(path, crFolderName);
					out.print(resultInfo);
				}
			}//end
				//Create file
			else if ((request.getParameter("submit") != null)
					&& ("CreateFile".equals(request.getParameter("parameter")))) {
				String crFileName = request.getParameter("crFileName");
				path = request.getParameter("path");//如果path以POST发过来就不要过滤了
				String crFilePath = path + File.separator + crFileName;
				if (path == null || path.length() < 1) {
					out.print("<div class='error'>没有获得当前路径</div>");
				} else if (crFileName == null || crFileName.length() < 1) {
					out.print("<div class='error'>没有获得创建文件的名称</div>");
				} else {
					resultInfo = FileOperation.crFile(path, crFileName);
					out.print(resultInfo);
				}
			}//end
				//rename
			else if ((request.getParameter("submit") != null)
					&& ("Rename".equals(request.getParameter("parameter")))) {
				String oldFileName = request.getParameter("oldFileName");
				String newFileName = request.getParameter("newFileName");
				path = request.getParameter("path");//如果path以POST发过来就不要过滤了
				if (path == null || path.length() < 1) {
					out.print("<div class='error'>没有获得当前路径</div>");
				} else if (oldFileName == null || oldFileName.length() < 1) {
					out.print("<div class='error'>请先点击文件右边的\"重命名\"连接</div>");
				} else if (newFileName == null || newFileName.length() < 1) {
					out.print("<div class='error'>没有获得文件的新名称</div>");
				} else {
					resultInfo = FileOperation.reName(path, oldFileName, newFileName);
					out.print(resultInfo);
				}
			}//end
				//upload file
			else if ((request.getContentType() != null)
					&& (request.getContentType().toLowerCase()
							.startsWith("multipart"))) {
				//if(request.getContentLength()>(1024*1024)){
				//out.print("<div class='error'>不能上传size大于1MB</div>");
				//}else{
				File ff = null;
				FileOutputStream ffos = null;
				int l = 0, l2 = 0;
				int startlineLength = 0;//边界符长度
				long filesize = 0;
				byte[] buffout = new byte[1024 * 10];
				byte[] buff = new byte[1024 * 10];
				String savepathname = null;
				String fileName = null;//文件名
				String startline = null;//第一行
				String filenameline = null;//文件名行(第二行)
				String endline = null;//最后一行
				String middleline = null;//中间行
				String exInfo = "";
				boolean issuccess = false;
				boolean isEnd = false;
				ServletInputStream sis = null;
				try {
					sis = request.getInputStream();
					//读第1行
					startlineLength = sis.readLine(buff, 0, buff.length);
					//如果第一行<3
					if (startlineLength < 3) {
						out.print("<div class='error'>读取第一行错误</div>");
					} else {
						startline = new String(buff, 0, startlineLength - 2);//得到第一行作为结尾行的依据
						endline = startline + "--";//结尾行比第一行多"--"
						//读第2行
						l = sis.readLine(buff, 0, buff.length);
						filenameline = new String(buff, 0, l);//得到第二行作为文件名的依据
						if (filenameline.indexOf("filename=\"") == -1) {
							out.print("<div class='error'>没有发现http头文件的filename</div>");
						} else {
							filenameline = FileOperation.getReqValue(filenameline, "filename");
							fileName = filenameline.substring(filenameline.lastIndexOf(File.separator) + 1);
							//fileName=getFileName(filenameline);
							if (fileName == null || fileName.length() < 1) {
								out.print("<div class='error'>没有发现要上传文件的文件名</div>");
							} else {
								if (!path.endsWith(File.separator)) {
									path = path + File.separator;
								}
								savepathname = path + fileName;
								ff = new File(savepathname);
								//如果文件已经存在
								if (ff.exists()) {
									sis.close();
									out.print("<div class='error'>不能上传到此路径:["
											+ savepathname + "],文件已存在</div>");
								} else {
									l = sis.readLine(buff, 0, buff.length);//读第3行
									l = sis.readLine(buff, 0, buff.length);//读第4行(空行)
									ffos = new FileOutputStream(ff);
									l2 = sis.readLine(buffout, 0,
											buffout.length);//读取内容第一行放入输出缓冲
									//读其他行
									while ((l = sis.readLine(buff, 0,
											buff.length)) != -1) {
										//判断是否最后一行,比较长度比比较字符串使用更小的系统开销
										if (l == (startlineLength + 2)
												|| l == (startlineLength + 2)) {
											middleline = new String(buff, 0, l);
											if (middleline.startsWith(endline)) {
												isEnd = true;
											}
										}
										if (isEnd) {
											ffos.write(buffout, 0, l2 - 2);
											break;
										} else {
											ffos.write(buffout, 0, l2);
											for (int i = 0; i < buff.length; i++) {
												buffout[i] = buff[i];
											}
											l2 = l;
										}
									}//while的结尾
									filesize = ff.length();
									out.print("<div class='success'>1个文件已上传:["
											+ savepathname + "],size:["
											+ FileOperation.convertFileSize(filesize)
											+ "(" + filesize + "字节)]</div>");
								}//else
							}//else
						}//else
					}//else
				} catch (Exception ulex) {
					out.print("<div class='error'>错误:" + ulex.getMessage()
							+ "</div>");
				}
				//关闭流
				if (ffos != null) {
					ffos.flush();
					ffos.close();
				}
				if (sis != null)
					sis.close();
				//}//else
			}//else

			//start view filelist
			int objFileError = 0;
			File objFile = new File(path);
			URLpath = URLEncoder.encode(path);
			String fileAbsolutePath = null;
			String encodeFileAbsolutePath = null;
		%>
		<script type="text/javascript" src="hands.js"></script>
		<table width="100%" cellpadding="0" cellspacing="0">
			<tr>
				<td colspan="2">
					当前路径:<%=FileOperation.path2link(path)%><br>
				</td>
			</tr>
			<tr>
				<td>
					<%
						if (objFile.getParent() == null) {
							out.print("<a href='#' disabled>已是最顶层目录</a> |");
						} else {
							out.print("<a href='" + FileOperation.LUCY + "?path="
									+ URLEncoder.encode(objFile.getParent())
									+ "'>上一级目录</a>  |");
						}
						SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-d H:mm");
						int a = 0, b = 0;
					%>
					<a href='#' onClick="history.go(-1);">后退</a> |
					<a href='#' onClick="history.go(1);">前进</a> |
					<a href="<%=FileOperation.LUCY%>?path=<%=URLpath%>">刷新</a> |
					<a href="<%=FileOperation.LUCY%>">返回</a>
				</td>
				<td align="right">
					文件名过滤:
					<input name="filt" type="text" class="text" onKeyUp="filter(this);">
				</td>
			</tr>
		</table>
		<form action="<%=FileOperation.LUCY%>" method="POST" name="FileList">
			<input id="parameter" type="hidden" name="parameter" value=""/>
			<div style="background-color: #DEDEDE">
				<table width="100%" cellpadding="1" cellspacing="1" id="Filetable">
					<thead>
						<tr bgcolor="#CCCCCC">
							<td width="2%" align="center">
								<input name="selall" type="checkbox"
									onClick="selectAll(this.form);" class="checkbox">
							</td>
							<td width="49%">
								名称:
							</td>
							<td width="9%">
								大小:
							</td>
							<td width="17%">
								最后修改:
							</td>
							<td width="5%">
								编辑:
							</td>
							<td width="8%">
								重命名:
							</td>
							<td width="10%">
								下载:
							</td>
						</tr>
					</thead>
					<tbody>
						<%
							File fileList[] = objFile.listFiles();
							if (fileList != null)
								Arrays.sort(fileList);
							if (fileList == null) {
								out.print("<tr><td colspan='7' bgcolor='#FFA2A2'>路径错误或其他错误,导致不能创建文件列表<br>尝试手动输入此路径:");
								out.print("<form action="
										+ FileOperation.LUCY
										+ " method='post'><input type='text' name='errorPath' size='50' class='text'>&nbsp;");
								out.print("<input type='submit' value='submit' class='button2'></form></td></tr></table></div>");
							} else {
								for (int i = 0; i < fileList.length; i++) {
									if (fileList[i].isDirectory()) {
										a++;
										fileAbsolutePath = fileList[i].getAbsolutePath();
										encodeFileAbsolutePath = URLEncoder
												.encode(fileAbsolutePath);
						%>
						<tr style="background-color: #FFFFFF"
							onMouseOver="selectRow(this,0);" onMouseOut="selectRow(this,1);"
							onMouseUp="selectRow(this,2);">
							<td align="center">
								<input type="checkbox" name="selfile"
									value="<%=fileAbsolutePath%>" onMouseDown="dis();"
									class="checkbox">
							</td>
							<td>
								<img src='folder.gif' align="absmiddle"
									style="margin-left: 4px;">
								<a href="<%=FileOperation.LUCY%>?path=<%=encodeFileAbsolutePath%>"
									onMouseDown="dis();"> <%=fileList[i].getName()%></a>
							</td>
							<td>
								文件夹
							</td>
							<td><%=formatter.format(fileList[i].lastModified())%></td>
							<td>
								-
							</td>
							<td>
								<a href="#tool" onMouseDown="dis();"
									onClick="showDivValue('rename','<%=fileList[i].getName()%>');">重命名</a>
							</td>
							<td>
								-
							</td>
						</tr>
						<%
							}//end if
								}//end for
								for (int i = 0; i < fileList.length; i++) {
									if (fileList[i].isFile()) {
										b++;
										fileAbsolutePath = fileList[i].getAbsolutePath();
										encodeFileAbsolutePath = URLEncoder
												.encode(fileAbsolutePath);
						%>
						<tr style="background-color: #FFFFFF"
							onMouseOver="selectRow(this,0);" onMouseOut="selectRow(this,1);"
							onMouseUp="selectRow(this,2);">
							<td align="center">
								<input type="checkbox" name="selfile"
									value="<%=fileAbsolutePath%>" onMouseDown="dis();"
									class="checkbox">
							</td>
							<td>
								<img src='file.gif' align="absmiddle" style="margin-left: 4px;">
								<a href="<%=FileOperation.VIEWER%>?path=<%=encodeFileAbsolutePath%>"
									onMouseDown="dis();" target="_blank"> <%=fileList[i].getName()%></a>
							</td>
							<td><%=FileOperation.convertFileSize(fileList[i].length())%></td>
							<td><%=formatter.format(fileList[i].lastModified())%></td>
							<td>
								<a href="<%=FileOperation.EDITOR%>?path=<%=encodeFileAbsolutePath%>"
									onMouseDown="dis();" target="_blank">编辑</a>
							</td>
							<td>
								<a href="#tool" onMouseDown="dis();"
									onClick="showDivValue('rename','<%=fileList[i].getName()%>');">重命名</a>
							</td>
							<td>
								<a href="<%=FileOperation.LUCY%>?download=<%=encodeFileAbsolutePath%>"
									onMouseDown="dis();">下载</a>
							</td>
						</tr>
						<%
							}//end if
								}//end for
						%>
					</tbody>
				</table>
			</div>
			<%
				}
			%>
			<div style="background-color: #CCCCCC;">
				统计:
				<img src='folder.gif' align="absmiddle">
				:<%=a%>,
				<img src='file.gif' align="absmiddle">
				:<%=b%>
				(过滤结果:
				<img src='folder.gif' align="absmiddle">
				:
				<span id="folderTotal"><%=a%></span>,
				<img src='file.gif' align="absmiddle">
				:
				<span id="fileTotal"><%=b%></span>)
			</div>
			<br>
			<a name="tool"></a>
			<b style="color: #666666">操作选中的文件:</b>
			<br>
			<input type="hidden" name="path" value="<%=path%>">
			<span id="Div_MoveFile_span"> <a href="#tool"
				onClick="javascript:showDiv('MoveFile');">移动</a> </span>|
			<span id="Div_CopyFile_span"> <a href="#tool"
				onClick="javascript:showDiv('CopyFile');">拷贝</a> </span>|
			<span id="Div_Delete_span"> <a href="#tool"
				onClick="javascript:showDiv('Delete');">删除</a> </span>|
			<span> <a href="#tool" onClick="javascript:disableAll();">隐藏工具按钮</a>
			</span>
			<!--Move File-->
			<div id="Div_MoveFile"
				style="display: none; margin-top: 3px; LETTER-SPACING: 0px">
				<b>移动文件(Move File)</b>
				<br>
				移动选中的文件到你填写的目标路径下
				<br>
				请输入移动的目标路径(如 "c:\abc\"):
				<br>
				<input type="text" name="mvFilePath" size="90" class="text">
				<br>
				<input type="submit" name="submit" value="移动文件" class="button2">
				<hr>
			</div>
			<!---->
			<!--Copy File-->
			<div id="Div_CopyFile"
				style="display: none; margin-top: 3px; LETTER-SPACING: 0px">
				<b>复制文件(Copy File)</b>
				<br>
				复制选中的文件到你填写的目标路径下
				<br>
				请输入复制的目标路径(如 "c:\abc\"):
				<br>
				<input type="text" name="cpFilePath" size="90" class="text">
				<br>
				<input type="submit" name="submit" value="拷贝文件" class="button2">
				<hr>
			</div>
			<!---->
			<!--Delete File-->
			<div id="Div_Delete"
				style="display: none; margin-top: 3px; LETTER-SPACING: 0px">
				<b>删除文件(Delete File)</b>
				<br>
				这是一项危险的操作,文件一旦被删除就不能恢复了
				<br>
				强烈建议你重新检查一次选中的文件,或者使用重命名代替删除.
				<br>
				如果你确定要这么做,点击下面按钮,选中的文件将被彻底删除.
				<br>
				<input type="submit" name="submit" class="button2" value="删除"
					onClick="return confirm('你确定要删除这些文件?')">
				<hr>
			</div>
			<!---->
		</form>
		<div style="margin-top: 3px; color: #666666;">
			<b>操作当前目录:</b>
		</div>
		<span id="Div_upload_span"> <a href="#tool"
			onClick="javascript:showDiv('upload');">上传</a> </span>|
		<span id="Div_newfolder_span"> <a href="#tool"
			onClick="javascript:showDiv('newfolder');">创建目录</a> </span>|
		<span id="Div_newfile_span"> <a href="#tool"
			onClick="javascript:showDiv('newfile');">创建文件</a> </span>|
		<span id="Div_rename_span"> <a href="#tool"
			onClick="javascript:showDiv('rename');">重命名</a> </span>
		<!--upload-->
		<div id="Div_upload"
			style="display: none; margin-top: 3px; LETTER-SPACING: 0px">
			<b>上传文件(Upload)</b>
			<br>
			你将上传一个文件到:
			<font color=red><%=path%></font>
			<br>
			<form method="POST"
				action="<%=FileOperation.LUCY%>?path=<%=URLEncoder.encode(path)%>"
				enctype="multipart/form-data">
				<input type="file" name="upfile" size="50" class="text">
				<br>
				<input type="submit" value="上传" class="button2">
			</form>
			<hr>
		</div>
		<!---->
		<!--Create Folder-->
		<div id="Div_newfolder"
			style="display: none; margin-top: 3px; LETTER-SPACING: 0px">
			<b>创建一个新文件夹(Create Folder)</b>
			<br>
			你将创建一个新文件夹在:
			<font color=red><%=path%></font>
			<br>
			<form method="POST" action="<%=FileOperation.LUCY%>">
				<input type="hidden" name="parameter" value="CreateFolder"/>
				<input type="hidden" name="path" value="<%=path%>">
				please enter新文件夹的名称:(不要含有 \ / : * ? " < > |)
				<br>
				<input type="text" name="crFolderName" size="50" class="text">
				<br>
				<input type="submit" name="submit" value="创建文件夹" class="button2">
			</form>
			<hr>
		</div>
		<!---->
		<!--Create File-->
		<div id="Div_newfile"
			style="display: none; margin-top: 3px; LETTER-SPACING: 0px">
			<b>创建一个新文件(Create File)</b>
			<br>
			你将创建一个新文件在:
			<font color=red><%=path%></font>
			<br>
			<form method="POST" action="<%=FileOperation.LUCY%>">
				<input type="hidden" name="parameter" value="CreateFile"/>
				<input type="hidden" name="path" value="<%=path%>">
				please enter新文件的名称: (如"abc.txt",并且不要含有 \ / : * ? " < > |)
				<br>
				<input type="text" name="crFileName" size="50" class="text">
				<br>
				<input type="submit" name="submit" value="创建文件" class="button2">
			</form>
			<hr>
		</div>
		<!---->
		<!--rename-->
		<div id="Div_rename"
			style="display: none; margin-top: 3px; LETTER-SPACING: 0px">
			<b>重命名一个文件夹或文件(Rename)</b>
			<br>
			你将重命名一个文件夹或文件在:
			<font color=red><%=path%></font>
			<br>
			<form method="POST" action="<%=FileOperation.LUCY%>">
				<input type="hidden" name="parameter" value="Rename"/>
				<input type="hidden" name="path" value="<%=path%>">
				<input type="hidden" id="Div_rename_hidden" name="oldFileName">
				请先点击文件列表右边对应的"重命名"连接,然后在此对话框中更改文件名称:(不要含有 \ / : * ? " < > |)
				<br>
				<input type="text" id="Div_rename_input" name="newFileName"
					size="50" class="text">
				<br>
				<input type="submit" name="submit" value="重命名" class="button2">
			</form>
			<hr>
		</div>
	</body>
</html>